import os
from pathlib import Path
from dotenv import load_dotenv

# 加载根目录下的.env文件
base_dir = Path(__file__).resolve().parent.parent
dotenv_path = base_dir / '.env'
if dotenv_path.exists():
    load_dotenv(dotenv_path=str(dotenv_path))


class Config:
    """基础配置"""
    APP_DEBUG = os.getenv('APP_DEBUG', False)

    # 文件存储
    RUNTIME_DIR = os.getenv('RUNTIME_DIR', 'runtime')
    LOG_ROTATE_SIZE = int(os.getenv('LOG_ROTATE_SIZE', 10 * 1024 * 1024))  # 默认10MB

    # 数据库配置
    DATABASE_TYPE = os.getenv('DATABASE_TYPE', 'mysql')
    DATABASE_HOSTNAME = os.getenv('DATABASE_HOSTNAME', '127.0.0.1')
    DATABASE_NAME = os.getenv('DATABASE_NAME', 'xsframe')
    DATABASE_USERNAME = os.getenv('DATABASE_USERNAME', 'root')
    DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD', 'root')
    DATABASE_PORT = os.getenv('DATABASE_PORT', '3306')
    DATABASE_PREFIX = os.getenv('DATABASE_PREFIX', 'ims_')

    # 缓存类型
    CACHE_DRIVER = os.getenv('CACHE_DRIVER', 'redis')
    CACHE_HOST = os.getenv('CACHE_HOST', '127.0.0.1')
    CACHE_PORT = os.getenv('CACHE_PORT', '6379')
    CACHE_PASSWORD = os.getenv('CACHE_PASSWORD', '')
    CACHE_DB = os.getenv('CACHE_DB', '0')
    CACHE_PREFIX = os.getenv('CACHE_PREFIX', 'xsframe')
    CACHE_FILE_PATH = os.getenv('CACHE_FILE_PATH', 'runtime/tmp/flask_limiter')

    # 动态蓝图配置
    @staticmethod
    def get_app_config(app_name):
        """获取应用特定配置"""
        return {
            'log_level': os.getenv(f'{app_name.upper()}_LOG_LEVEL', 'INFO'),
            'max_requests': int(os.getenv(f'{app_name.upper()}_MAX_REQUESTS', 1000))
        }


class DevelopmentConfig(Config):
    FLASK_ENV = 'development'
    APP_DEBUG = True
    PREFERRED_URL_SCHEME = 'http'


class ProductionConfig(Config):
    FLASK_ENV = 'production'
    APP_DEBUG = False
    PREFERRED_URL_SCHEME = 'https'


def get_config():
    """根据环境变量选择配置类"""
    env = os.getenv('FLASK_ENV', 'development')
    return {
        'development': DevelopmentConfig,
        'production': ProductionConfig
    }.get(env, DevelopmentConfig)
